package cn.iocoder.yudao.module.erp.controller.admin.departquantity;

import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.erp.controller.admin.departquantity.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.departquantity.DepartQuantityDO;
import cn.iocoder.yudao.module.erp.service.departquantity.DepartQuantityService;

@Tag(name = "管理后台 - 带量分配")
@RestController
@RequestMapping("/erp/depart-quantity")
@Validated
public class DepartQuantityController {

    @Resource
    private DepartQuantityService departQuantityService;

    @PostMapping("/create")
    @Operation(summary = "创建带量分配")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:create')")
    public CommonResult<Long> createDepartQuantity(@Valid @RequestBody DepartQuantitySaveReqVO createReqVO) {
        DepartQuantitySaveReqVO dqs = new DepartQuantitySaveReqVO();
        int quantity = 0;
        departQuantityService.deleteForProduct(createReqVO.getProductId());
        for(int i =0;i<createReqVO.getDepts().size();i++){
            if(null != createReqVO.getDepts().get(i).getCount() && !("").equals(createReqVO.getDepts().get(i).getCount())){
                quantity +=createReqVO.getDepts().get(i).getCount();
            }
        }
        if(createReqVO.getDepts().size()== 0 ){
            int quantityCount = 0;
            if(null !=createReqVO.getQuantityCount() && !("").equals(createReqVO.getQuantityCount())){
                quantityCount = Integer.parseInt(createReqVO.getQuantityCount());
            }

            dqs.setAllocationStatus(quantityCount-quantity);
            dqs.setProductId(createReqVO.getProductId());
            dqs.setProductName(createReqVO.getProductName());
            dqs.setCategoryId(createReqVO.getCategoryId());
            dqs.setUnitId(createReqVO.getUnitId());
            dqs.setStandard(createReqVO.getStandard());
            dqs.setBarCode(createReqVO.getBarCode());
            dqs.setDeptId(null);
            dqs.setCount(null);
            dqs.setQuantityCount(createReqVO.getQuantityCount());
            dqs.setTaskStartTime(createReqVO.getTaskStartTime());
            dqs.setTaskEndTime(createReqVO.getTaskEndTime());
            departQuantityService.createDepartQuantity(dqs);
        }else{
            for(DeptDO dp :  createReqVO.getDepts()){
                int quantityCount = 0;
                if(null !=createReqVO.getQuantityCount() && !("").equals(createReqVO.getQuantityCount())){
                    quantityCount = Integer.parseInt(createReqVO.getQuantityCount());
                }
                dqs.setAllocationStatus(quantityCount-quantity);
                dqs.setProductId(createReqVO.getProductId());
                dqs.setProductName(createReqVO.getProductName());
                dqs.setCategoryId(createReqVO.getCategoryId());
                dqs.setUnitId(createReqVO.getUnitId());
                dqs.setStandard(createReqVO.getStandard());
                dqs.setBarCode(createReqVO.getBarCode());
                dqs.setDeptId(dp.getId());
                dqs.setCount(dp.getCount());
                dqs.setQuantityCount(createReqVO.getQuantityCount());
                dqs.setTaskStartTime(createReqVO.getTaskStartTime());
                dqs.setTaskEndTime(createReqVO.getTaskEndTime());
                departQuantityService.createDepartQuantity(dqs);
            }
        }
        return success(createReqVO.getId());
    }

    @PutMapping("/update")
    @Operation(summary = "更新带量分配")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:update')")
    public CommonResult<Boolean> updateDepartQuantity(@Valid @RequestBody DepartQuantitySaveReqVO updateReqVO) {
        departQuantityService.updateDepartQuantity(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除带量分配")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:delete')")
    public CommonResult<Boolean> deleteDepartQuantity(@RequestParam("id") Long id) {
        departQuantityService.deleteDepartQuantity(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得带量分配")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:query')")
    public CommonResult<DepartQuantityRespVO> getDepartQuantity(@RequestParam("id") Long id) {
        DepartQuantityDO departQuantity = departQuantityService.getDepartQuantity(id);
        return success(BeanUtils.toBean(departQuantity, DepartQuantityRespVO.class));
    }

    @GetMapping("/getQuantity")
    @Operation(summary = "获得带量分配")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:query')")
    public CommonResult<List<DepartQuantityRespVO>> getQuantity(@RequestParam("id") Long id) {
        List<DepartQuantityRespVO> departQuantity = departQuantityService.getQuantity(id);
        return success(departQuantity);
    }

    @GetMapping("/page")
    @Operation(summary = "获得带量分配分页")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:query')")
    public CommonResult<PageResult<DepartQuantityRespVO>> getDepartQuantityPage(@Valid DepartQuantityPageReqVO pageReqVO) {
        PageResult<DepartQuantityDO> pageResult = departQuantityService.getDepartQuantityPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DepartQuantityRespVO.class));
    }
    @GetMapping("/getDeptPage")
    @Operation(summary = "获得带量分配分页")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<List<DeptListReqVO>> getDeptPage(@Valid DeptListReqVO pageReqVO) {
        List<DeptDO> pageResult = departQuantityService.getDeptPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DeptListReqVO.class));
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出带量分配 Excel")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDepartQuantityExcel(@Valid DepartQuantityPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DepartQuantityDO> list = departQuantityService.getDepartQuantityPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "带量分配.xls", "数据", DepartQuantityRespVO.class,
                        BeanUtils.toBean(list, DepartQuantityRespVO.class));
    }

    // ==================== 子表（部门） ====================

    @GetMapping("/dept/list-by-id")
    @Operation(summary = "获得部门列表")
    @Parameter(name = "id", description = "部门id")
    @PreAuthorize("@ss.hasPermission('erp:depart-quantity:query')")
    public CommonResult<List<DeptDO>> getDeptListById(@RequestParam("id") Long id) {
        return success(departQuantityService.getDeptListById(id));
    }

}